#include <Windows.h>
#include <stdlib.h>
#include <time.h>
#include "Controller.h"
#include "Definitions.h"

HINSTANCE g_hInst;
HWND g_wndHandle;

bool initWindow(HINSTANCE);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
	srand((int)time(NULL));
	initWindow(hInstance);
	g_hInst = hInstance;

	Controller control;

	MSG msg;
	ZeroMemory(&msg, sizeof(msg));
	while(msg.message!=WM_QUIT)
	{
		//check for messages
		while( PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) )
		{
			TranslateMessage( &msg );
			DispatchMessage( &msg );
		}
		//when no messages
		//update
		if(!control.Update())
			PostQuitMessage(0);
		//render
		control.Render();
	}
	return msg.wParam;
}

bool initWindow(HINSTANCE hInstance)
{
	WNDCLASSEX wcex;

	wcex.cbSize = sizeof(WNDCLASSEX);
	wcex.style			= CS_HREDRAW | CS_VREDRAW;
	wcex.lpfnWndProc	= (WNDPROC)WndProc;
	wcex.cbClsExtra		= 0;
	wcex.cbWndExtra		= 0;
	wcex.hInstance		= hInstance;
	wcex.hIcon			= 0;
	wcex.hCursor		= LoadCursor(NULL, IDC_ARROW);
	wcex.hbrBackground	= (HBRUSH)(COLOR_WINDOW+1);
	wcex.lpszMenuName	= NULL;
	wcex.lpszClassName	= "Space Shooter";
	wcex.hIconSm		= 0;
	RegisterClassEx(&wcex);

	//create RECT that will pass in correct window values to CreateWindow function
	RECT windowRect;
	windowRect.left = windowRect.top = 0;
	windowRect.right = SCREEN_WIDTH;
	windowRect.bottom = SCREEN_HEIGHT;
	//this function adjust the window to be exactly your screen width/height w/o the chrome affecting the size
	::AdjustWindowRect(&windowRect, WS_OVERLAPPEDWINDOW, FALSE);

	g_wndHandle = CreateWindow("Space Shooter", "Space Shooter", WS_OVERLAPPEDWINDOW, 0, 0, windowRect.right-windowRect.left, windowRect.bottom-windowRect.top, NULL, NULL, hInstance, NULL);
	if (!g_wndHandle)
		return false;

	ShowWindow(g_wndHandle, SW_SHOW);
	UpdateWindow(g_wndHandle);

	return true;
}

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	switch (message)
	{
	case WM_DESTROY:	PostQuitMessage(0);	break;
	}
	return DefWindowProc(hWnd, message, wParam, lParam);
}